# coding:utf-8
__author__ = '啦拉嘿'
__date__ = '2020/3/2 22:54'
import os, django
# 配置其他py文件正常使用djangoORM
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_orm.settings")
django.setup()
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import datetime
from PIL import ImageTk, Image
import requests
import json
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import random

from connect_db.models import Category, UseTime, User
from connect_db.views import today_distribute_time_classify_by_category
from setting import Setting
from panel import DisplayMenu
from Tk_lib.commond_lib import TreeViewTable, random_beautiful_color


class MenuBar:
    def __init__(self, root, user):
        # 用户
        self.__root = root
        self.__user = user
        self.__menu_bar = tk.Menu(self.__root)
        self.__setting_menu = tk.Menu(self.__menu_bar, tearoff=0)
        self.__setting_menu.add_command(label="添加计时类", command=self.__set_setting_command)
        # self.__setting_menu.add_separator() 添加分割线
        self.__display_model_menu = tk.Menu(self.__menu_bar, tearoff=0)
        self.__display_model_menu.add_command(label="展示统计图", command=self.__set_display_menu_command)
        self.__user_menu = tk.Menu(self.__menu_bar, tearoff=0)
        self.__user_menu.add_command(label=self.__user)
        self.__menu_bar.add_cascade(label="设置", menu=self.__setting_menu)
        self.__menu_bar.add_cascade(label="展示", menu=self.__display_model_menu)
        self.__menu_bar.add_cascade(label="用户", menu=self.__user_menu)
        self.__root.config(menu=self.__menu_bar)

    def __set_setting_command(self):
        setting = Setting(self.__root)
        setting.display()

    def __set_display_menu_command(self):
        test = DisplayMenu(user=self.__user)
        test.display()
        test.root.mainloop()

    def set_user(self, user):
        self.__user = user

    def get_user(self):
        return self.__user


class Timer:
    def __init__(self):
        """
        strftime('%Y-%m-%d %H:%M:%S')
        """
        self.__root = tk.Tk()
        self.__menubar = None
        self.__login_text = tk.StringVar()
        self.__image = ImageTk.PhotoImage(Image.open('media/assignment.jpg').resize((870, 500)))

        self.__ttk_label_frame = ttk.Labelframe(self.__root, text="开始使用时间：")
        self.__label = ttk.Label(self.__ttk_label_frame, text=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        self.__start_button = ttk.Button(self.__root, text="开始", command=self.__set_start_button_function)
        self.__is_start = False
        self.__start_time = None

        # 下拉菜单
        self.__combo_box_ttk_frame = ttk.Labelframe(self.__root, text="选择类型")
        self.__combo_box_label = ttk.Label(self.__combo_box_ttk_frame, text="计时类型")
        self.__combo_box = ttk.Combobox(self.__combo_box_ttk_frame)
        self.__combo_box_list = Category.objects.order_by('-add_time')
        self.__combo_box["value"] = list(self.__combo_box_list)
        self.__combo_box.current(0)

        # 数据表格
        self.__table = None

    def __update_figure(self):
        f = plt.Figure()
        gs = GridSpec(2, 2, figure=f)
        plt.style.use('ggplot')
        plt.rcParams['font.sans-serif'] = ['SimHei']
        f.suptitle("今日时间分布")
        sum_use_time = 0

        subfig1 = f.add_subplot(gs[0, :])
        data = today_distribute_time_classify_by_category()
        color = random_beautiful_color()
        pie_colors = []
        for i in data:
            sum_use_time += data[i]["total_use"]
            choice_color = random.choice(color)
            pie_colors.append(choice_color)
            color.remove(choice_color)

            subfig1.plot(data[i]["time"], data[i]["use"], label=i, c=choice_color)
        subfig1.legend(loc='upper right')

        ax1 = f.add_subplot(gs[1, 0])
        ax1.pie([sum_use_time, 10.5-sum_use_time], labels=["用时", "未用时"], autopct='%1.0f%%',
                textprops=dict(color="#FFFFFF00"))
        ax1.legend(loc="center right", bbox_to_anchor=(1, 0, 0.3, 1))
        ax1.axis('equal')

        ax2 = f.add_subplot(gs[1, 1])
        ax2.pie([data[i]["total_use"] for i in data], labels=[i for i in data], autopct='%1.0f%%', colors=pie_colors,
                textprops=dict(color="w"))
        ax2.legend(loc="center right", bbox_to_anchor=(1, 0, 0.3, 1))
        ax2.axis('equal')

        return f

    def __set_start_button_function(self):
        if self.__is_start:
            self.__is_start = not self.__is_start

            user = User.objects.get(user=self.__menubar.get_user())

            category = Category.objects.get(category=self.__combo_box_list[self.__combo_box.current()])
            category.use_number += 1
            category.save()

            connect_use_time_db = UseTime()
            connect_use_time_db.user = user
            connect_use_time_db.category = category
            connect_use_time_db.start_time = self.__start_time
            connect_use_time_db.stop_time = datetime.datetime.now()
            connect_use_time_db.use_time = (datetime.datetime.now() - self.__start_time).seconds / 3600
            try:
                connect_use_time_db.save()
            except Exception as e:
                messagebox.showerror("存储错误", e)

            # 更新表格
            self.__table.destroy()
            self.__table = ttk.Labelframe(self.__root, text="今日详细信息", width=500, height=500)
            self.__table.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
            FigureCanvasTkAgg(self.__update_figure(), self.__table).get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH,
                                                                                         expand=1)

            self.__label.configure(text=connect_use_time_db.use_time)
            self.__label.configure(background="white")
            self.__start_button.config(text="开始")
            self.__combo_box['state'] = "normal"
        else:
            self.__is_start = not self.__is_start
            self.__start_time = datetime.datetime.now()
            self.__label.configure(text="开始时间" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            self.__label.configure(background="red")
            self.__start_button.config(text="停止")
            self.__combo_box['state'] = "disabled"

    def _set_window(self):
        self.__root.minsize(width=700, height=400)
        self.__root.maxsize(width=700, height=400)
        # self.__root.maxsize(width=400, height=400)

        # 下拉菜单
        self.__combo_box_ttk_frame.pack(side=tk.TOP, padx=10, pady=10, fill=tk.X, ipadx=5, ipady=5)
        self.__combo_box_label.pack(side=tk.LEFT, padx=10)
        self.__combo_box.pack(side=tk.LEFT, padx=10, fill=tk.X, expand=True)

        self.__start_button.pack(side=tk.BOTTOM, pady=5, padx=5, ipadx=3, ipady=3)

        self.__ttk_label_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10, ipadx=5, ipady=5)
        self.__label.pack(side=tk.TOP, fill=tk.X)

        # 今日时间使用表格
        self.__table = ttk.Labelframe(self.__root, text="今日详细信息", width=500, height=500)
        self.__table .pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        FigureCanvasTkAgg(self.__update_figure(), self.__table).get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def display(self):
        self._set_window()

    def login(self, e, login_box, user_list, **kwargs):
        current_user = user_list[login_box.current()]
        self.__menubar = MenuBar(self.__root, current_user)
        login_box.destroy()
        for i in kwargs:
            kwargs[i].destroy()
        e.widget.destroy()

        self.display()

    def login_page(self):
        login_frame = tk.Frame(self.__root, width=200)
        login_label = ttk.Label(login_frame, text="用户", font=('华文行楷', 30, "bold"))
        login_box = ttk.Combobox(login_frame)
        user = list(User.objects.order_by('use_number'))
        login_box["value"] = user
        login_box.current(0)
        login_button = ttk.Button(login_frame, text="登入")
        self.__login_text.set("倒计时：" + str((datetime.datetime.strptime('2020-12-20', '%Y-%m-%d')
                                            - datetime.datetime.now()).days) + "天")
        img_Lab = tk.Label(login_frame, textvariable=self.__login_text, compound='center', font=('华文楷体', 30, "bold"),
                           image=self.__image, fg="red")

        login_button.bind("<1>", lambda e: self.login(e, login_box, user, wi1=login_frame, w2=login_label))

        # display
        login_frame.pack(side=tk.LEFT, fill=tk.BOTH)
        login_frame.propagate(0)
        img_Lab.grid(row=1, column=1, rowspan=3)
        login_label.grid(row=1, column=2)
        login_box.grid(row=2,  column=2, ipadx=5, ipady=5, padx=5, pady=5)
        login_button.grid(row=3, column=2, ipadx=15, ipady=5, padx=5, pady=5)

        # 每日一句
        result = request()
        english = ttk.Label(login_frame, text=result["content"], font=('微软雅黑', 10, "bold"))
        translation = ttk.Label(login_frame, text=result["note"], font=('微软雅黑', 10, "bold"))
        english.grid(row=4, column=1, columnspan=2, padx=5, pady=5)
        translation.grid(row=5, column=1, columnspan=2, padx=5, pady=5)

        self.__root.mainloop()


def request():
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    try:
        response = requests.get("http://open.iciba.com/dsapi/", timeout=1)
    except:
        return {"content": "网络未连接", "note": "网络未连接"}
    return response.json()


if __name__ == '__main__':
    main = Timer()
    main.login_page()
